#include "include/widgets/report_widget.hpp"
#include <QHeaderView>

ReportWidget::ReportWidget(TradingSystem *tradingSystem, QWidget *parent)
    : QWidget(parent), m_tradingSystem(tradingSystem) {
  setupUI();
  setupConnections();
  refreshTransactionTable();
}

void ReportWidget::setupUI() {
  // 创建主布局
  auto *mainLayout = new QVBoxLayout(this);

  // 创建交易记录表格
  m_transactionTableView = new QTableView(this);
  m_transactionModel = new QStandardItemModel(this);
  m_transactionModel->setColumnCount(6);
  m_transactionModel->setHorizontalHeaderLabels(
      {"时间", "类型", "代码", "名称", "数量", "价格", "金额"});

  m_transactionTableView->setModel(m_transactionModel);
  m_transactionTableView->horizontalHeader()->setSectionResizeMode(
      QHeaderView::Stretch);
  m_transactionTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
  m_transactionTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
  m_transactionTableView->setSortingEnabled(true);

  // 刷新按钮
  auto *buttonLayout = new QHBoxLayout();
  m_refreshButton = new QPushButton("刷新", this);
  buttonLayout->addStretch();
  buttonLayout->addWidget(m_refreshButton);

  // 将控件添加到布局
  mainLayout->addWidget(m_transactionTableView);
  mainLayout->addLayout(buttonLayout);
}

void ReportWidget::setupConnections() {
  connect(m_refreshButton, &QPushButton::clicked, this,
          &ReportWidget::refreshTransactionTable);
}

void ReportWidget::refreshTransactionTable() {
  // 清空表格
  m_transactionModel->removeRows(0, m_transactionModel->rowCount());

  UserAccount *account = m_tradingSystem->getCurrentAccount();
  if (!account) {
    return;
  }

  // 添加交易记录
  const QVector<TransactionRecord> &records = account->getTransactionHistory();
  for (const auto &record : records) {
    QList<QStandardItem *> row;

    // 时间
    row.append(
        new QStandardItem(record.getTime().toString("yyyy-MM-dd hh:mm:ss")));

    // 类型
    auto *typeItem = new QStandardItem(record.getTypeString());
    if (record.getType() == TransactionRecord::Type::Buy) {
      typeItem->setForeground(QBrush(Qt::red));
    } else {
      typeItem->setForeground(QBrush(Qt::green));
    }
    row.append(typeItem);

    // 代码和名称
    row.append(new QStandardItem(record.getStockCode()));
    row.append(new QStandardItem(record.getStockName()));

    // 数量
    auto *sharesItem = new QStandardItem();
    sharesItem->setData(record.getShares(), Qt::DisplayRole);
    row.append(sharesItem);

    // 价格
    auto *priceItem = new QStandardItem();
    priceItem->setData(record.getPrice(), Qt::DisplayRole);
    row.append(priceItem);

    // 金额
    auto *totalItem = new QStandardItem();
    totalItem->setData(record.getTotal(), Qt::DisplayRole);
    row.append(totalItem);

    m_transactionModel->appendRow(row);
  }

  // 按时间降序排序
  m_transactionTableView->sortByColumn(0, Qt::DescendingOrder);
}
